import util from '../common/util.js';
import config from './config.js';
function Client(api_url,img_url,app_name,coordinate,map_key) {
    this.API_URL = api_url;
    this.IMG_URL = img_url;
	this.AppName = app_name;
	this.coordinate = coordinate;
	this.MAP_KEY = map_key;
    //GET请求方式
    this.get = function(action, params, callback, failback, auth) {
        this.ajax('get', action, params, callback, failback, auth);
    };

    //POST请求方式
    this.post = function(action, params, callback, failback, auth) {
        this.ajax('post', action, params, callback, failback, auth);
    };

    //请求前参数处理
    this.ajax = function(method, action, params, callback, failback, auth) {
		uni.showNavigationBarLoading();
	
        //判断请求地址是否为空
        if (typeof action != 'string' || action == '') {
            //console.log('请求地址不能为空');
            return;
        }

        //判断params是否function，是则赋值给callback并设置params为null
        if (typeof params === 'function') {
            if (callback === 'auth') {
                auth = 'auth';
            }
            callback = params;
            params = null;
        }

        //判断params是否为null，是则设置为空对象
        if (params === null) {
            params = {};
        }
		
		var authheader = {};
		
		// if(method == 'get'){
			authheader = {"content-type": "application/json",token:uni.getStorageSync("token"),loginFrom:'app'};
			
		// }else if(method == 'post'){
		// 	authheader =  {'content-type': 'application/x-www-form-urlencoded'};
		// }
		if (auth) {
			// if(uni.getStorageSync("key")&&uni.getStorageSync("secret")) {
			if(uni.getStorageSync("token")){
			   // var key = uni.getStorageSync("key") || '';
			   // var secret = uni.getStorageSync("secret") || '';
			   var token =uni.getStorageSync("token") || '';
			   var loginFrom ='app';
			   var timestamp = Math.round(new Date().getTime()/1000).toString();
			   var sign = util.getSign(params,timestamp,token,loginFrom);
			   authheader = Object.assign(authheader, {sign:sign,timestamp:timestamp});//添加请求头
			   // console.log(authheader,"请求头")
			} else {
			    //跳转到登录页
				//console.log('11'+uni.getStorageSync('toLogin')+'2')
				if(!(uni.getStorageSync('toLogin'))){
					uni.setStorageSync('toLogin',true);
					//console.log(222)
					uni.navigateTo({
					    url: "/pages/hrlogin/hrlogin"
					});
					failback();
					uni.hideNavigationBarLoading();
					return;
				}else{
					failback();
					uni.hideNavigationBarLoading();
					return;
				}
			}
		}
		//console.log(params);
		//console.log(authheader);
        uni.request({
            url: api_url + action,
            data: params,
            method: method,
            dataType: "json",
        	timeout:10000,
        	header:authheader,
            success: function(response) {
        		uni.hideNavigationBarLoading();
        		//console.log(response);
        		if (response.data.code == 200) {
        			if(typeof callback === 'function'){
						if(response.data.total || response.data.totalPages){
							callback(response.data.data, response.data.msg,response.data.total,response.data.totalPages);
						}else{
							callback(response.data.data, response.data.msg);
						}
        				// callback(response.data.data, response.data.msg);
        			}
        			return;
        		} else if (response.data.code === 401) {
        			util.showToast({title:'登录失效，请重新登录再操作！'});
        			uni.setStorageSync('token', '');
        			uni.navigateTo({
        			    url: "/pages/hrlogin/hrlogin"
        			});
        			failback();
        			return;
        		}else if (response.data.code === 500) {
                   failback(response.data.msg);
                    return;
                }
        		else {
        			if(typeof failback === 'function'){
        				failback(response.data.msg);
        			}
        			return;
        		}
            },
            fail: function(error) {
        		uni.hideNavigationBarLoading();
        		if (error.response) {
        			if(typeof error.response == 'string'){
        				util.showToast({title:error.response});
        			}
        			if(typeof failback === 'function'){
        				failback(error.response);
        			}
        			return;
        		} else {
        			util.showToast({title:'网络错误'});
        			if(typeof failback === 'function'){
        				failback();
        			}
        			return;
        		}
            }
        });
    };

}
var client = new Client(config.api_url,config.img_url,config.app_name,config.coordinate,config.map_key);
export {client};
